package humynn.engine
{
	import flash.display.BitmapData;
	import flash.events.MouseEvent;
	import flash.geom.Rectangle;
	import flash.media.Sound;

	/**
	 * The button class creates a UI control that responds to the mouse.
	 */
	public class Button extends Control
	{
		private var _oldlmb:Boolean;
		
		/**
		 * The Button constructor.
		 * 
		 * @param file The image file to use for the button
		 * @param x The initial x location of the button @default 0
		 * @param y The initial y location of the button @default 0
		 */
		public function Button(file:String, x:int = 0, y:int = 0)
		{
			super();
			
			_oldlmb = true;
			
			_imageFile = file;
			
			_rect.x = x;
			_rect.y = y;
			_rect.width = ImageManager.getTileWidth(_imageFile);
			_rect.height = ImageManager.getTileHeight(_imageFile);
			
			_animIndex = 0;
		}
		
		/**
		 * Gets the animation index for the button.
		 * 
		 * @returns The animation index.
		 */
		public function get animation():uint
		{
			return _animIndex;
		}
		
		/**
		 * Sets the animation index for the button.
		 * 
		 * @param value The new animation index.
		 */
		public function set animation(value:uint):void
		{
			_animIndex = value;
		}
		
		/**
		 * Updates the button state every frame
		 * 
		 * @param input The input data used to update the button with
		 */
		public override function update(input:Input):void
		{
			if(_rect.contains(input.mouse.x, input.mouse.y))
			{
				_animFrame = 1;
				
				if(input.mouse.lmbutton && !_oldlmb)
				{
					var event:MouseEvent = new MouseEvent(MouseEvent.CLICK);
					dispatchEvent(event);

					SoundManager.play("click.mp3");
				}
			}
			else
			{
				_animFrame = 0;
			}
			
			_oldlmb = input.mouse.lmbutton;
		}
									  
	}
}